/*
 *@本JS功能：添加班级
 *@本js作者：杨锡君
 *@编写时间：2017年10月30日
 */
$(function() {
	var Alert1 = new Alert();
	var confirm1 = new Confirm();
	var $addBtn = $(".classAddBtn");
	var $delBtn = $(".classDelBtn");
	var $className = $(".className");
	var $departNames = $("#departNames");
	var $profession = $("#profession");
	var $saveClass = $(".saveClass");
	var $publicCancleBtn = $(".publicCancleBtn");
	var classAddModel = "<div class=\"addClassBoxes\" value=\"1\">" +
		"<div class=\"rightMargin fl\">" +
		"<label class=\"fl labelRight\">添加课程:</label>" +
		"<select class=\"publicSelect course\">" +
		"<option value=\"0\">请选择</option>" +
		"</select>" +
		"</div>" +
		"<span class=\"clear\"></span>" +
		"<div class=\"rightMargin fl\">" +
		"<label class=\"fl labelRight\">选择教师:</label>" +
		"<select class=\"publicSelect tea\">" +
		"<option value=\"0\">请选择</option>" +
		"</select>" +
		"</div>" +
		"</div>";

	var addClass = {
		init: function() {
			var self = this;
            maxLengthLimit.init("className");
			var json = JSON.stringify({
				"pageNow": 1,
				"pageSize": 10
			});
			$.ajax({
				type: "post",
				url: "getClassList",
				data: {
					"jsonStr": json
				},
				async: true,
				success: function(msg) {
                    msg = JSON.parse(msg);
					self.courseList = msg.courseList;
					self.teacherList = msg.teacherList;
					//					院系获取
					$.map(msg.departMentList, function(opt) {
						$departNames.append("<option value=" + opt.departmentId + " >" + opt.departmentName + "</option>");
					});
					//					院系联动
					$departNames.change(function() {
						var deppartmentId = $departNames.val();
						self.departmentChange(deppartmentId);
					});
					//课程获取
					$.map(self.courseList, function(opt) {
						$(".course").append("<option value=" + opt.courseId + ">" + opt.courseName + "</option>");
					});
					//老师获取
					$.map(self.teacherList, function(opt) {
						$(".tea").append("<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>");
					});
					self.bindEvent(self.courseList, self.teacherList);
				}
			});
		},
		bindEvent: function(courseList, teacherList) {
			var self = this;
			//			添加课程与教师
			$addBtn.off("click").click(function() {
				self.addClassEvent(courseList, teacherList);
			});
			//			删除
			$delBtn.off("click").click(function() {
				self.delClassEvent();
			});
			//			保存
			$saveClass.off("click").click(function() {
				var flag = self.verifications();
				if(flag) {
					self.saveClassEvent();
				}

			});
			//取消
			$publicCancleBtn.click(function() {
                var json = JSON.stringify({
                    "pageName": "adminClassMana"
                });
                window.location.href = "skipPage?jsonStr=" + json;
			});
		},
		saveClassEvent: function() {
            var className = $className.val();
            var professionId = Number($profession.val());
            var json = {
                "className": className,
                "professionId": professionId
            };
            if($(".addClassBoxes").length == 1 && $(".course").val() == 0 && $(".tea").val() === "0"){
                json = {
                    "className": className,
                    "professionId": professionId
                };
			}else{
                var arr = [];
                var opt = {}

                $.each($(".addClassBoxes"), function(opt) {
                    var stu = $(this).children("div:last").children("select:first").val();
                    var cid = Number($(this).children("div:first").children("select:first").val());
                    arr.push({
                        "stuorteaId": stu,
                        "courseId": cid
                    });
                });
                json.relationList = arr;
			}
			json = JSON.stringify(json);
			//			Loading1.show();
			//执行异步提交表单
			$.ajax({
				type: 'post',
				url: 'addClass',
				data: {
					"jsonStr": json
				},
				success: function(msg) {
					//					Loading1.hide();
                    msg = JSON.parse(msg);
					if(msg.result == "success") {
						Alert1.content = "添加班级成功";
						Alert1.success = function() {
							var json = JSON.stringify({
								"pageName": "adminClassMana"
							});
							window.location.href = "skipPage?jsonStr=" + json;
						};
						Alert1.init();
						Alert1.show();

					} else {
						//						Loading1.hide();
						Alert1.content = msg.failMsg;
						Alert1.init();
						Alert1.show();
					}
				},
				error: function() {
					Alert1.content = "提交失败！";
					Alert1.init();
					Alert1.show();
				}
			});
		},
		departmentChange: function(deppartmentId) {
			if(deppartmentId != 0) {
				var json = {
					"departmentId": deppartmentId
				};
				json = JSON.stringify(json);
				$.ajax({
					type: "post",
					url: "getProfessionListByDepmentId",
					data: {
						"jsonStr": json
					},
					async: true,
					success: function(msg) {
                        msg = JSON.parse(msg);
						$profession.empty();
						$profession.append("<option value=\"0\">请选择</option>");
						if(msg.professionList != null && msg.professionList.length != 0) {
							$.map(msg.professionList, function(opt) {
								$profession.append('<option value ="' + opt.professionId + '">' + opt.professionName + '</option>');
							});
						}
					},
                    error:function () {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;
                    }
				});
			}
		},
		verifications: function() {
			//			验证
			var self = this;
			var classNameVal = $className.val();
			if(classNameVal == "") {
				Alert1.content = "请输入班级名称";
				Alert1.init();
				Alert1.show();
				return false;
			}
			var flag = verification.spaceCode(classNameVal);
			var flags = verification.specialCode(classNameVal);
			if(flag != true) {
				Alert1.content = flag;
				$className.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			if(flags != true) {
				Alert1.content = flags;
				$className.val("");
				Alert1.init();
				Alert1.show();
				return false;
			}
			var departMentSel = $departNames.val();

			if(departMentSel == 0) {
				Alert1.content = "请选择院系";
				Alert1.init();
				Alert1.show();
				return false;
			}
			var professionSel = $profession.val();

			if(professionSel == 0) {
				Alert1.content = "请选择专业";
				Alert1.init();
				Alert1.show();
				return false;
			}
			if($(".addClassBoxes").length == 1 && $(".course").val() == 0 && $(".tea").val() === "0"){
                return true;
			}else{
                var array2 = [];
                var s;
                var c;
                $.each($(".addClassBoxes"), function(opt) {
                    var stu = $(this).children("div:last").children("select:first").val();
                    var cid = Number($(this).children("div:first").children("select:first").val());
                    s = true;
                    c = true;
                    if(cid == 0) {
                        Alert1.content = "请将教师教课信息补充完整";
                        Alert1.init();

                        Alert1.show();
                        c = false;
                        return false;

                    }
                    if(stu === "0") {

                        Alert1.content = "请将教师信息补充完整";
                        Alert1.init();

                        Alert1.show();
                        s = false;
                        return false;

                    }

                    array2.push({
                        "stuorteaId": stu,
                        "courseId": cid
                    });
                });
                var yn = self.indexof(array2);

                if(yn == true) {
                    Alert1.content = "存在重复课程请修改";
                    Alert1.init();
                    Alert1.show();
                    return false;
                }
                if(s && c) {
                    return true;
                }
			}

		},
		indexof: function(arr) {

			var hash = {};
			for(var i in arr) {
				if(hash[arr[i].courseId])
					return true;
				hash[arr[i].courseId] = true;
			}
			return false;

		},
		delClassEvent: function() {
			if($(".addClassBoxes").length == 1) {
				return false;
			}
			$(".addClassBoxes:last").remove();
		},
		addClassEvent: function(courseList, teacherList) {
			$(".addClassBoxes").attr("value", "0");
			$(".classBox").append(classAddModel);
			//课程获取
			$.map(courseList, function(opt) {
				$(".addClassBoxes[value=\"1\"]>div:first>.course").append("<option value=" + opt.courseId + ">" + opt.courseName + "</option>");
			});
			//老师获取
			$.map(teacherList, function(opt) {
				$(".addClassBoxes[value=\"1\"]>div:last>.tea").append("<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>");
			});
		}
	};
	addClass.init();
});